  <template>
    <view class="content">
      <view class="custom-nav-bar" :style="{ height: navBarHeight + 'px' }">
        <!-- 状态栏占位（避免内容被时间、信号栏覆盖） -->
        <view :style="{ height: statusBarHeight + 'px' }"></view>
        <!-- 导航栏内容（标题+图标） -->
        <view class="nav-content" :style="{ height: navBarContentHeight + 'px' }">
          <!-- 返回键 -->
          <view class="back-wrapper" :class="{ active: getFocusIndex() === 0 }" tabindex="-1"
            @click="goBack">
            <image class="nav-icon" src="/static/right.png" style="transform: rotate(180deg);" />
          </view>
          <!-- 标题 -->
          <text class="nav-title">消息通知</text>
          <!-- 设置页面跳转 -->
          <!-- <view class="setting-wrapper" :class="{ active: focusNavigator.getCurrentIndex() === 1 }" tabindex="-1"
            @click="goToSetting">
            <image class="nav-icon" src="/static/setting-white.png" />
          </view> -->
          <image class="nav-icon" src="/static/filter-white.png"
            :class="{ active: getFocusIndex() === 1 }" tabindex="-1" />
        </view>
      </view>

      <!-- tab切换消息列表 -->
      <view class="tab-bar" :style="{ top: navBarHeight + 'px' }">
        <view class="tab-item"
          :class="[currentTab === 'unRead'?'active':'', getFocusIndex() === 2 ? 'keyboard-active' : '']"
          tabindex="-1" @click="switchTab('unRead')">
          未读信息({{unReadAmount}})
        </view>
        <view class="divider"></view>
        <view class="tab-item"
          :class="[currentTab === 'Read'?'active':'', getFocusIndex() === 3 ? 'keyboard-active' : '']"
          tabindex="-1" @click="switchTab('Read')">
          已读信息
        </view>
      </view>

      <!-- 页面主体内容（需添加 padding-top 避免被导航栏覆盖） -->
      <view class="page-content" :style="{ paddingTop: (navBarHeight + tabBarHeight) + 'px' }">
        <!-- 加载状态 -->
        <view class="loading-fallback" v-if="isLoading">
          <text>加载中...</text>
        </view>
        
        <!-- 页面内容 -->
        <view class="" v-else-if="currentTab==='unRead'">
          <!-- <view class="list-unReadcontainer"> -->
          <!-- 滚动容器：必须指定高度和滚动方向 -->
          <scroll-view class="scroll-container" scroll-y="true" direction="vertical" @scrolltolower="loadMore(false)"
            :scroll-with-animation="false" :style="{ height:scrollHeight + 'px' }">
            <!-- 未读信息列表 -->
            <view class="chat-item" v-for="(item, index) in unReadList" :key="index">
              <!-- 未读内容区域 -->
              <view class="chat-content">
                <navigator :url="`/pages/messageContent/messageContent?id=${item.id}&title=${item.title}`"
                  @click="changeReadStatus(item.id)" tabindex="-1"
                  :class="[currentTab === 'Read'?'active':'', getFocusIndex() === 4+index ? 'keyboard-active' : '']">
                  <view class="chat-title">
                    <text class="chat-name">{{ item.title }}</text>
                    <image class="chat-icon" src="/static/right.png" mode=""></image>
                  </view>
                </navigator>
                <!-- <text class="chat-desc">{{ item.desc }}</text> -->
                <view class="chat-bottom">
                  <!-- 消息时间 -->
                  <text class="chat-type" :style="{color:'#eee'}">{{item.type}}</text>
                  <text class="chat-time">{{ item.createTime }}</text>
                  <!-- <text class="chat-type" :style="{color:'#eee'}">{{item.type}}</text> -->
                </view>
                <view class="divider"></view>
              </view>
            </view>

            <!-- 加载状态提示 -->
            <view class="loading" v-if="loading">
              加载中...
            </view>
            <view class="loading" v-if="noMore">
              没有更多数据了
            </view>
          </scroll-view>
          <!-- </view> -->
        </view>
        <view class="" v-else-if="currentTab==='Read'">
          <!-- <view class="list-Readcontainer"> -->
          <scroll-view class="scroll-container" scroll-y="true" direction="vertical" @scrolltolower="loadMore(true)"
            :scroll-with-animation="false" :style="{ height:scrollHeight + 'px' }">
            <view class="chat-item" v-for="(item, index) in ReadList" :key="index">
              <!-- 已读内容区域 -->
              <view class="chat-content">
                <navigator :url="`/pages/messageContent/messageContent?id=${item.id}&title=${item.title}`" tabindex="-1"
                  :class="[getFocusIndex() === 4+index ? 'keyboard-active' : '']">
                  <view class="chat-title">
                    <text class="chat-name">{{ item.title }}</text>
                    <image class="chat-icon" src="/static/right.png" mode=""></image>
                  </view>
                </navigator>
                <!-- <text class="chat-desc">{{ item.desc }}</text> -->
                <view class="chat-bottom">
                  <!-- 消息时间 -->
                  <text class="chat-type" :style="{color:'#eee'}">{{item.type}}</text>
                  <text class="chat-time">{{ item.createTime }}</text>
                </view>
                <view class="divider"></view>
              </view>
            </view>
            <!-- </view> -->

            <!-- 加载状态提示 -->
            <view class="loading" v-if="loading">
              加载中...
            </view>
            <view class="loading" v-if="noMore">
              没有更多数据了
            </view>

          </scroll-view>
        </view>
      </view>
    </view>
  </template>

  <script setup>
    import {
      ref,
      onMounted,
      onUnmounted,
      watch
    } from 'vue'
    import {
      onLoad,
      onShow,
      onPullDownRefresh
    } from '@dcloudio/uni-app'
    import {
      getReadList,
      changeStatus
    } from '../../apis/apis.js'
    import {
      createFocusNavigator
    } from '../../utils/key.js'

  // 已读未读栏切换
  const currentTab = ref('unRead')
  const unReadList = ref([]);
  const ReadList = ref([])
  const unReadAmount = ref(0)
  const isLoading = ref(false) // 添加加载状态

    // 分页状态
    const page = ref(1)
    const pageSize = ref(5)

    // 加载状态
    const loading = ref(false)
    const noMore = ref(false)

    // 导航栏高度相关变量
    const statusBarHeight = ref(0) // 状态栏高度
    const navBarContentHeight = ref(44) // 导航栏内容高度 (单位: px)
    const navBarHeight = ref(0) // 导航栏总高度 (状态栏高度 + 导航栏内容高度)
    const tabBarHeight = ref(40) // TabBar 高度 (单位: px)
    const scrollHeight = ref(0)

    // 控制下拉框显示/隐藏
    // const showDropdown = ref(false)
    // 当前筛选类型（用于内容区过滤）
    // const currentFilter = ref('all')
    // 设备编号
    let deviceNo = ""

    // 动态焦点项与导航器
    const focusItems = ref([])
    let focusNavigator = null

    const openMessage = (item) => {
      changeReadStatus(item.id)
      uni.navigateTo({ url: `/pages/messageContent/messageContent?id=${item.id}&title=${item.title}` })
    }

    const unregisterKeys = (navigatorInstance) => {
      try {
        const sys = uni.getSystemInfoSync();
        if (sys.platform === 'android' && navigatorInstance) {
          plus.key.removeEventListener('keydown', navigatorInstance.handleKeyDown);
          plus.key.removeEventListener('keyup', navigatorInstance.handleKeyUp);
        }
      } catch (e) {}
    }

    const registerKeys = (navigatorInstance) => {
      const sys = uni.getSystemInfoSync();
      if (sys.platform === 'android' && navigatorInstance) {
        plus.key.addEventListener('keydown', navigatorInstance.handleKeyDown);
        plus.key.addEventListener('keyup', navigatorInstance.handleKeyUp);
      }
    }

    const rebuildFocusItems = () => {
      const items = [
        { name: '返回键', onSelect: () => goBack() },
        { name: '筛选' },
        { name: '未读信息', onSelect: () => switchTab('unRead') },
        { name: '已读信息', onSelect: () => switchTab('Read') },
      ]
      if (currentTab.value === 'unRead') {
        (unReadList.value || []).forEach((item, idx) => {
          items.push({ name: `未读-${idx}`, onSelect: () => openMessage(item) })
        })
      } else {
        (ReadList.value || []).forEach((item, idx) => {
          items.push({ name: `已读-${idx}`, onSelect: () => openMessage(item) })
        })
      }
      focusItems.value = items

      const prevIndex = Math.min(focusNavigator?.getCurrentIndex?.() ?? 0, 3)
      unregisterKeys(focusNavigator)
      if (focusNavigator) focusNavigator.destroy()
      focusNavigator = createFocusNavigator(focusItems.value, prevIndex)
      registerKeys(focusNavigator)
    }

    // 兼容渲染期间 focusNavigator 可能为 null 的情况
    const getFocusIndex = () => {
      try {
        return focusNavigator && typeof focusNavigator.getCurrentIndex === 'function'
          ? focusNavigator.getCurrentIndex() : 0
      } catch (e) { return 0 }
    }

    // 返回上一页
    const goBack = () => {
      uni.navigateBack();
    };

    // 跳转到设置页面
    const goToSetting = () => {
      uni.navigateTo({
        url: '/pages/Setting/Setting'
      });
    };

    // Tab栏切换
    const switchTab = (tabName) => {
      page.value = 1
      currentTab.value = tabName;
      getUnReadList()
      getIsReadList()
      // 根据当前tab更新焦点项
      setTimeout(rebuildFocusItems, 0)
    };

    onLoad(() => {
      // 获取屏幕信息
      const systemInfo = uni.getSystemInfoSync()

      // 设置状态栏高度 (兼容不同平台)
      statusBarHeight.value = systemInfo.statusBarHeight || systemInfo.safeAreaInsets?.top || 20
      // 计算导航栏总高度
      navBarHeight.value = statusBarHeight.value + navBarContentHeight.value
      scrollHeight.value = systemInfo.windowHeight - statusBarHeight.value - navBarHeight.value - tabBarHeight
        .value

    })
    // 页面刷新时获取消息列表
  onShow(() => {
    try {
      isLoading.value = true
      
      deviceNo = uni.getStorageSync('deviceNo')
      console.log('deviceNo:', deviceNo)
      
      // 先构建焦点，确保基础UI可显示
      setTimeout(() => {
        rebuildFocusItems()
        isLoading.value = false
      }, 100)
      
      if (deviceNo) {
        // 并行请求，避免阻塞页面渲染
        setTimeout(() => {
          Promise.all([
            getUnReadList(),
            getIsReadList()
          ]).catch(error => {
            console.error('数据加载失败:', error)
            uni.showToast({
              title: '数据加载失败',
              icon: 'none',
              duration: 2000
            })
          })
        }, 200)
      } else {
        uni.showToast({
          title: '设备编号未设置',
          icon: 'none',
          duration: 2000
        })
      }
    } catch (error) {
      console.error('onShow执行出错:', error)
      isLoading.value = false
    }
  })

    // 开启键盘监听
    onMounted(() => {
      const sys = uni.getSystemInfoSync();
      // 初始构建焦点项与导航器
      rebuildFocusItems()
    });

    // 移除键盘监听器
    onUnmounted(() => {
      const sys = uni.getSystemInfoSync();
      if (sys.platform === 'android' && focusNavigator) {
        plus.key.removeEventListener('keydown', focusNavigator.handleKeyDown);
        plus.key.removeEventListener('keyup', focusNavigator.handleKeyUp);
      }
      focusNavigator && focusNavigator.destroy();
    });

    // 列表与tab变化时重建焦点项
    watch([currentTab, unReadList, ReadList], () => {
      setTimeout(rebuildFocusItems, 0)
    }, { deep: true })

    // 选择筛选条件后关闭下拉框（弃用）
    // const handleFilter = (type) => {
    //   currentFilter.value = type
    //   showDropdown.value = false // 选择后隐藏下拉框
    //   // 此处可添加筛选逻辑（如过滤unReadList/ReadList）
    //   // console.log('隐藏：', showDropdown.value)
    //   page.value = 1
    //   getUnReadList()
    //   getIsReadList()
    // }

    // 监听下拉刷新事件
    onPullDownRefresh(() => {
      // 下拉时重新请求数据（先清空列表，再重新获取）
      console.log('触发下拉刷新')
      uni.showToast({
        title: '下拉刷新',
        icon: 'success',
        duration: 2000
      })
      page.value = 1;

      // 先清空当前列表（可选，根据需求决定）
      unReadList.value = []
      ReadList.value = []

      // 重新请求未读和已读列表
      Promise.all([
        getUnReadList(), // 重新获取未读列表
        getIsReadList() // 重新获取已读列表
      ]).then(() => {
        // 数据请求完成后，停止下拉刷新动画
        uni.stopPullDownRefresh()
      }).catch((error) => {
        console.error('刷新失败：', error)
        // 即使失败，也需停止刷新动画
        uni.stopPullDownRefresh()
      })
    })

    // 上拉加载更多
    const loadMore = async (isRead) => {

      // 避免重复加载或无更多数据时触发
      if (loading.value || noMore.value) return

      uni.showToast({
        title: '成功加载',
        icon: 'success',
        duration: 2000
      })
      loading.value = true
      page.value++

      // const res = await getUnReadList()
      try {
        const res = await getReadList({
          orderByColumn: "",
          orderByAsc: true,
          pageIndex: page.value,
          pageSize: pageSize.value,
          keyword: "",
          eqCode: deviceNo,
          isRead: isRead
        })

        const newData = res.data.list || []
        // 去掉筛选逻辑，直接使用新数据
        let currentList = []
        if (!isRead) {
          unReadList.value = [...unReadList.value, ...newData] // 合并新数据
          currentList = unReadList.value

        } else {
          ReadList.value = [...ReadList.value, ...newData] // 合并新数据
          currentList = ReadList.value
        }
        const total = res.data.total || 0 // 总数据条数
        const currentTotal = currentList.length + newData.length // 当前累计加载条数
        noMore.value = currentTotal >= total; // 累计条数 >= 总条数 → 无更多数据
      } catch (error) {
        console.error('上拉加载失败：', error)
      } finally {
        loading.value = false // 无论成功失败，结束加载状态
      }
    }
    // 获取未读列表
    async function getUnReadList() {
      try {
        if (!deviceNo) {
          console.log('deviceNo为空，跳过未读列表请求')
          return
        }
        
        const res = await getReadList({
          orderByColumn: "",
          orderByAsc: true,
          pageIndex: page.value,
          pageSize: pageSize.value,
          keyword: "",
          eqCode: deviceNo,
          isRead: false
        })
        console.log('未读列表为', res.data)
        unReadAmount.value = res.data.total || 0
        if (unReadList.value.length !== res.data.list.length) {
          // 去掉筛选逻辑，直接显示所有数据
          unReadList.value = res.data.list || []
          // 重置加载状态
          noMore.value = (res.data.list || []).length < pageSize.value
        }
      } catch (error) {
        console.error('获取未读列表失败：', error);
        unReadList.value = []
        unReadAmount.value = 0
      }
    }
    // 获取已读列表
    async function getIsReadList() {
      try {
        if (!deviceNo) {
          console.log('deviceNo为空，跳过已读列表请求')
          return
        }
        
        const res = await getReadList({
          orderByColumn: "",
          orderByAsc: true,
          pageIndex: 1,
          pageSize: 10,
          keyword: "",
          eqCode: deviceNo,
          isRead: true
        })
        console.log('已读列表为', res.data)
        // 去掉筛选逻辑，直接显示所有数据
        ReadList.value = res.data.list || []
      } catch (error) {
        console.error('获取已读列表失败：', error);
        ReadList.value = []
      }
    }
    // 更改未读消息状态
    async function changeReadStatus(id) {
      try {
        if (!deviceNo) {
          console.log('deviceNo为空，无法更改消息状态')
          return
        }
        
        console.log('转换id为', id)
        await changeStatus({
          newsId: id,
          eqCode: deviceNo
        })
      } catch (error) {
        console.error('更改消息状态失败：', error)
      }
    }
  </script>

  <style>
    /* 核心安全区域样式（所有页面生效） */
    /* page { */
    /* padding-top: 20px; */
    /* } */

    /* 屏蔽原生选择框和焦点样式 */
    * {
      outline: none !important;
      box-shadow: none !important;
    }

    *:focus {
      outline: none !important;
      box-shadow: none !important;
    }

    .custom-nav-bar {
      position: fixed;
      /* 固定在顶部 */
      top: 0;
      left: 0;
      width: 100%;
      background-color: #333;
      /* 导航栏背景色 */
      /* box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1); */
      /* 阴影（可选） */
      z-index: 999;
      /* 确保在页面内容上方 */
    }

    .nav-content {
      display: flex;
      justify-content: space-between;
      /* 标题左对齐、图标右对齐 */
      align-items: center;
      padding: 12rpx 24rpx;
      /* 左右内边距 */
      box-sizing: border-box;
    }

    .nav-title {
      font-size: 48rpx;
      /* 标题字号 */
      font-weight: bold;
      /* 标题加粗（可选） */
      color: #fff;
      /* 标题颜色 */
      /* margin-left: 80rpx; */
      padding-bottom: 2px;
    }

    .nav-icon {
      width: 72rpx;
      /* 图标宽度（根据实际调整） */
      height: 72rpx;
      /* 图标高度（根据实际调整） */
      cursor: pointer;
      /* 鼠标指针样式（可选） */
    }

    /* 返回键样式 */
    .back-wrapper {
      width: 72rpx;
      height: 72rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }

    /* 设置按钮样式 */
    .setting-wrapper {
      width: 72rpx;
      height: 72rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }

    /* 键盘焦点高亮样式 */
    .active {
      background-color: #007AFF;
      border-radius: 8rpx;
      box-shadow: 0 0 10rpx rgba(0, 122, 255, 0.5) !important;
    }

    .keyboard-active {
      background-color: #fff !important;
      color: #000 !important;
      border-radius: 8rpx;
      box-shadow: 0 0 10rpx rgba(0, 122, 255, 0.5) !important;
    }

    /* 包裹filter图标和下拉框的容器（相对定位，作为下拉框的定位基准） */
    /* .filter-wrapper {
      position: relative;
      /* 与图标同尺寸，确保点击区域一致 */
    /* width: 72rpx;
      height: 72rpx;
    } */

    /* 下拉框样式 */
    /* .dropdown {
      /* 绝对定位，相对于filter-wrapper */
    /* position: absolute;
      top: 80rpx;
      /* 图标高度(72rpx) + 8rpx间距 */
    /* left: 0;
      width: 240rpx;
      /* 下拉框宽度 */
    /* background-color: #444;
      /* 与导航栏背景协调 */
    /* border: 1rpx solid #666;
      border-radius: 8rpx;
      z-index: 1000;
      /* 高于其他元素 */
    /* box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.3);
      /* 阴影增强层次感 */
    /* } */

    /* 下拉选项样式 */
    /* .dropdown-item {
      padding: 20rpx 32rpx;
      color: #fff;
      font-size: 40rpx;
      border-bottom: 1rpx solid #666;
    }

    .dropdown-item:last-child {
      border-bottom: none;
    }

    .dropdown-item:active {
      background-color: #555;
      /* 点击反馈 */
    /* } */

    .tab-bar {
      position: fixed;
      left: 0;
      /* top: 90rpx; */
      width: 100%;
      display: flex;
      height: 40px;
      border-top: 2px solid #888;
      border-bottom: 1px solid #666;
      background-color: #444;
      /* box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1); */
      /* 底部阴影区分内容区 */
      z-index: 998;
    }

    .tab-item.active {
      background-color: #eee;
      /* 选中时背景色（白色） */
      color: #000;
      /* 选中时文字颜色（黑色，对比明显） */
      font-weight: bold;
      /* 可选：加粗文字，增强视觉效果 */
    }

    .divider {
      width: 1rpx;
      height: 100%;
      background-color: #666;
    }

    .tab-item {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #eee;
      font-size: 18px;
      cursor: pointer;
    }

    .page-content {
      /* 页面内容样式（根据实际调整） */
      /* padding: 20rpx; */
      /* display: flex;
      flex-direction: column; */
      min-height: 100vh;
      background-color: #555;
      color: #fff;
      /* margin-top: 180rpx; */
    }

    .list-unReadcontainer,
    .list-Readcontainer {
      /* padding: 10px; */
    }

    .scroll-container {
      width: 100%;
      overflow-y: auto;
      /* 关键：计算滚动区域高度（屏幕高度 - 导航栏 - 标签栏） */
      /* 确保内容溢出时可滚动 */
    }

    .chat-item navigator {
      display: flex;
      flex-direction: row;
      align-items: center;
      padding: 4px 10px;
      pointer-events: none;
    }

    .chat-avater {
      width: 50px;
      height: 50px;
      border-radius: 4px;
      margin-right: 10px;
    }

    .chat-icon {
      width: 20px;
      height: 20px;
      border-radius: 4px;
      margin-right: 10px;
      z-index: 1;
    }

    .chat-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      border-bottom: 1px solid #888;
    }

    .chat-title,
    .chat-bottom {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 5px;
      margin-top: 5px;
    }

    .chat-name {
      font-size: 20px;
      font-weight: bold;
      color: #bbb;
    }

    .chat-time,
    .chat-type {
      font-size: 14px;
      color: #bbb;
    }

    .chat-desc {
      font-size: 14px;
      color: #eee;
      line-height: 1.4;
      /* margin-bottom: 8xp; */
    }

    /* 加载状态样式 */
    .loading-fallback {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      padding: 20px;
      background-color: rgba(0, 0, 0, 0.7);
      border-radius: 8px;
      color: #fff;
      font-size: 16px;
      z-index: 999;
    }
  </style>